﻿#include "httprequest.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QNetworkReply>
#include <QDebug>
#include <QVector>
#include <QDateTime>
#include <QApplication>
#include <QFile>
#include <QFileInfo>
#include <QTextCodec>
#include "common.h"
#include "systeminfomation.h"
#include "./src/gumbo/wrapper/Document.h"
#include "./src/gumbo/wrapper/Selection.h"
#include "./src/gumbo/wrapper/Node.h"

void test_parser() {
    std::string page("<h1><a>wrong link</a><a class=\"special\"\\>some link</a></h1>");
    CDocument doc;
    doc.parse(page.c_str());

    CSelection c = doc.find("h1 a.special");
    CNode node = c.nodeAt(0);
    qDebug() << "Node:" << node.text().c_str();
    std::string content = page.substr(node.startPos(), node.endPos()-node.startPos());
    qDebug() << "Node: " << content.c_str();
}

void test_html() {
    std::string page = "<html><div><span>1\n</span>2\n</div></html>";
    CDocument doc;
    doc.parse(page.c_str());
    CNode pNode = doc.find("div").nodeAt(0);
    std::string content = page.substr(pNode.startPos(), pNode.endPos() - pNode.startPos());
    qDebug() << "Node: " << content.c_str();
}

void test_escape() {
    std::string page = "<html><div><span id=\"that's\">1\n</span>2\n</div></html>";
    CDocument doc;
    doc.parse(page.c_str());
    CNode pNode = doc.find("span[id=\"that's\"]").nodeAt(0);
    std::string content = page.substr(pNode.startPos(), pNode.endPos() - pNode.startPos());
    qDebug() << "Node: " << content.c_str();
}


HttpRequest::HttpRequest()
{
    m_networkAccessManager = new QNetworkAccessManager();
    connect(m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), \
        this, SLOT(dealNetworkFinisheded(QNetworkReply*)));
    test_parser();
    test_html();
    test_escape();
}

HttpRequest::~HttpRequest()
{
    if(m_networkAccessManager) {
        delete m_networkAccessManager;
        m_networkAccessManager = nullptr;
    }
}

void HttpRequest::setUrls(RequestType type, const QString url)
{
    m_type = type;
    m_request.setUrl(url);
}

void HttpRequest::fillHttpRequest()
{
    auto strTimeStamp = SystemInfomation::genTimeStamp();
    auto uuid = SystemInfomation::get_nonce();
    //m_request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
//    m_request.setRawHeader("XX-TestCipher", SystemInfomation::getCipher().toUtf8());
//    m_request.setRawHeader("XX-Timestamp", strTimeStamp.toUtf8());
//    m_request.setRawHeader("XX-Nonce", uuid.toUtf8());
//    m_request.setRawHeader("XX-Signature", SystemInfomation::get_signature(strTimeStamp, uuid).toUtf8());
//    m_request.setRawHeader("XX-Version", SystemInfomation::getVersion().toUtf8());
}

void HttpRequest::fillDatas(const RequestType& type, const QString& url)
{
    m_mapUrl.insert(type, url);
}

void HttpRequest::getStockInfo(const QString& code)
{
    auto url = m_mapUrl.value(kDongFangCaiFuRequest) + "q=" + code;
    setUrls(kDongFangCaiFuRequest, url);
    m_networkAccessManager->get(m_request);
}

void HttpRequest::getRegionInfomation()
{
    fillHttpRequest();
    auto url = m_mapUrl.value(kRegionRequest);
    setUrls(kRegionRequest, url);
    m_networkAccessManager->get(m_request);
}

void HttpRequest::onSendRequestPost(const QByteArray& data)
{
    fillHttpRequest();
    auto url = m_mapUrl.value(kGaRequest);
    setUrls(kGaRequest, url);
    m_networkAccessManager->post(m_request, data);
}

void HttpRequest::dealNetworkFinisheded(QNetworkReply *reply)
{       
    QByteArray recvData = reply->readAll();
    QString error = reply->errorString();
    qInfo() << "recvData: " << recvData;
    reply->deleteLater();
    reply = nullptr;
    switch (type()) {
    case kDongFangCaiFuRequest: {
        auto parseString = QString::fromLocal8Bit(recvData);
        auto temp = parseString.mid(parseString.indexOf("="));
        // "1~ST\xB6\xAB\xB1\xB1\xB8\xDF~600003~3.87~3.87~0.00"
        QStringList list = temp.split("~");
        if(list.size() > 5) {
            qDebug() << list.value(0);
            qDebug() << list.value(1);
            qDebug() << list.value(2);
            qDebug() << list.value(3);
            qDebug() << list.value(4);
            emit signalStockInfomation(list.value(1), list.value(3));
        }
        qDebug() << parseString;
    }
        break;
    default:
        break;
    }

    //    common::debugJsonFormat(recvData);
    //    QJsonParseError jsonError;
    //    QJsonDocument document = QJsonDocument::fromJson(recvData, &jsonError);
    //    if (document.isObject() && (jsonError.error == QJsonParseError::NoError)) {
    //        qInfo()<<"send post data success!";
    //        int code = document.object().value("code").toInt();

    //    }
    //    else {
    //        qInfo()<<"send post data error:" + error;
    //        if(type() == kDongFangCaiFuRequest)
    //            emit signalRegionInfomation("");
    //    }
}
